package com.study.animationstudy.ui

import android.animation.ObjectAnimator
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.LinearLayout
import com.study.animationstudy.R
import com.study.animationstudy.base.BaseActivity
import com.study.animationstudy.databinding.ActivityShutterBinding
import com.study.animationstudy.util.Utils

class ShutterActivity : BaseActivity<ActivityShutterBinding>() {

    private val shutterArray = arrayOf("水平五叶", "水平十叶", "水平二十叶",
        "垂直五叶", "垂直十叶", "垂直二十叶")


    override fun ActivityShutterBinding.initBinding() {
        initView()
        initLayerSpinner()
    }

    private fun initView(){
        val bitmap = BitmapFactory.decodeResource(resources,R.drawable.dlam)
        // 设置百叶窗视图的位图对象
        mBinding.svShutter.setImageBitmap(bitmap)
        val params = mBinding.svShutter.layoutParams
        params.height = Utils.getScreenWidth(this) * bitmap.height / bitmap.width
        // 设置百叶窗视图的布局参数
        mBinding.svShutter.layoutParams = params
    }

    private fun initLayerSpinner(){
        val modeAdapter = ArrayAdapter(this,R.layout.item_select,shutterArray)
        mBinding.spShutter.apply {
            prompt = "请选择百叶窗动画类型"
            adapter = modeAdapter
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onItemSelected(
                    parent: AdapterView<*>?,
                    view: View?,
                    position: Int,
                    id: Long
                ) {
                    // 设置百叶窗视图的动画方向
                    mBinding.svShutter.setOriention(if (position<3) LinearLayout.HORIZONTAL else LinearLayout.VERTICAL)
                    if (position ==0 || position ==3){
                        // 设置百叶窗的叶片数量
                        mBinding.svShutter.setLeafCount(5)
                    } else if (position == 1 || position == 4){
                        mBinding.svShutter.setLeafCount(10)
                    } else if (position == 2 || position == 5){
                        mBinding.svShutter.setLeafCount(20)
                    }
                    // 构造一个按比率逐步展开的属性动画
                    val anim = ObjectAnimator.ofInt(mBinding.svShutter,"ratio",0,100)
                    // 设置动画的播放时长
                    anim.duration = 3000
                    anim.start()
                }
                override fun onNothingSelected(parent: AdapterView<*>?) {}
            }
            setSelection(0)
        }
    }
}